# -*- coding: utf-8 -*-
"""
Created on Wed Jul  5 14:53:21 2017

@author: Jocker
"""
from Utills import GetLog
import re_testify as re_head_test
import service as service
import paho.mqtt.client as mqtt
import json
#import LOG as logfile
#日志配置
log=GetLog()
#初始化mosquitto客户端
client = mqtt.Client(client_id="110", clean_session=False, userdata="manager_server")
client.connect("47.93.103.173", 1883, 60)
# The callback for when the client receives a CONNACK response from the server.
#service函数调用设置,便于功能扩展
#service_method_pool=["REG","LOGIN","LOGOUT","PING","USERLIST","CHAT","ADDFRIEND","DELFRIEND","LISTFRIEND","REGETSESSION"]
#转发处理字典
service_method={
"REG":service.REG_method,
"LOGIN":service.LOGIN_method,  
"LOGOUT":service.LOGOUT_method,                
"PING":service.PING_method,
"USERLIST":service.USERLIST_method,                  
"CHAT":service.CHAT_method,
"ADDFRIEND":service.ADDFRIEND_method,
"DELFRIEND":service.DELFRIEND_method,
"LISTFRIEND":service.LISTFRIEND_method,
"REGETSESSION":service.REGETSESSION_method
}
#请求头校验函数
re_method={
"REG":re_head_test.re_REG,
"LOGIN":re_head_test.re_LOGIN,  
"LOGOUT":re_head_test.re_LOGOUT,                
"PING":re_head_test.re_PING,
"USERLIST":re_head_test.re_USERLIST,                  
"CHAT":re_head_test.re_CHAT,
"ADDFRIEND":re_head_test.re_ADDFRIEND,
"DELFRIEND":re_head_test.re_DELFRIEND,
"LISTFRIEND":re_head_test.re_LISTFRIEND,
"REGETSESSION":re_head_test.re_REGETSESSION
}
#转发处理函数

def switch_function(request_data,request_method,request_version,head_test_result):
    service_method[request_method](request_data,client,head_test_result)
def on_connect(client, userdata, flags, rc):
    #print("Connected with result code "+str(rc))
    print("connect ok")
#    client.subscribe("/manage",0)
#    client.subscribe("/manage",1)
    client.subscribe("/manage",0)
#    client.publish("/listener", payload=None, qos=0, retain=False)
#    client.publish("/listener", payload=None, qos=1, retain=False)
    client.publish("/listener", payload=None, qos=0, retain=False)
    log.info("CONNECT:success"+str(rc))
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    #client.subscribe("$SYS/#")
def on_disconnect(client, userdata, rc):
    if rc != 0:
        print("Unexpected disconnection."+str(rc))
#        log.error("Unexpected disconnection:"+str(rc))
# The callback for when a PUBLISH message is received from the server.
def on_publish(client, userdata, mid):
    print(userdata+"publish ok")  
def on_message(client, userdata, msg):
    #解析json格式得到payload
	try: 
            request_data = json.loads(msg.payload.decode())
            print(request_data)
            log.info("R:"+json.dumps(request_data,ensure_ascii=False,indent=2))
            #请求method
            request_method=request_data.get("method")
            #请求版本号
            request_version=request_data.get("version")
            #过滤错误请求方法
            #method头验证
            if(isinstance(request_data,dict) and re_head_test.method_head(request_data)):
            #具体请求头验证
                head_test_result=re_method[request_method](request_data)
                if(head_test_result):
                #处理业务函数
                        		    head_test_result={"error":"0",
                        		                      "type":"HEAD_TEST",
                        		                      "message":"success",
                        		                      "version":request_version}
                else:
                                head_test_result={ 
                                        		 "error":"1",
                                        		 "type":"HEAD_TEST",
                                        		 "message":"请求头错误",
                                        		 "version":request_version
                                                 }
                #携带校验结果进入业务逻辑
                switch_function(request_data,request_method,request_version,head_test_result)           
                #method头错误引起直接抛弃
         
	except:
	     log.error("SERIOUS:NoneType_error")  
def on_subscribe(client, userdata, mid, granted_qos):
    print(userdata+"subscribe ok")
#client.unsubscribe("$SYS/#")
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect=on_disconnect
client.on_publish=on_publish
client.loop_forever()
#while True:
#    str = input()
#    if str:
#      
#        client.publish("/listener", payload="hello", qos=2, retain=False)
#        print("publish ok")
#client.disconnect()
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
